<script>
  import { onMount } from 'svelte';
  import { invoke } from '@tauri-apps/api/tauri';
  import { fade } from 'svelte/transition';
  
  // 状态管理
  let currentDistro = '检测中...';
  let mirrors = [];
  let selectedMirror = null;
  let isLoading = true;
  let errorMessage = '';
  
  // 获取系统信息
  const loadSystemInfo = async () => {
    try {
      currentDistro = await invoke('get_system_info');
    } catch (err) {
      errorMessage = `系统信息获取失败: ${err}`;
    }
  };

  // 获取镜像列表
  const loadMirrors = async () => {
    try {
      mirrors = await invoke('list_available_mirrors');
      mirrors = mirrors.map(m => ({ ...m, latency: null, testing: false }));
    } catch (err) {
      errorMessage = `镜像列表加载失败: ${err}`;
    } finally {
      isLoading = false;
    }
  };

  // 执行测速
  const runSpeedTest = async (mirror) => {
    mirror.testing = true;
    try {
      const latency = await invoke('test_mirror_speed', { 
        mirrorUrl: mirror.url 
      });
      mirrors = mirrors.map(m => 
        m.url === mirror.url ? { ...m, latency, testing: false } : m
      );
    } catch (err) {
      errorMessage = `测速失败: ${err}`;
      mirror.testing = false;
    }
  };

  // 切换镜像源
  const applyMirror = async (mirror) => {
    try {
      await invoke('switch_mirror', { mirrorUrl: mirror.url });
      alert(`已成功切换到 ${mirror.name}`);
      // 更新当前选中状态
      selectedMirror = mirror.url;
    } catch (err) {
      errorMessage = `镜像切换失败: ${err}`;
    }
  };

  // 初始化加载
  onMount(async () => {
    await loadSystemInfo();
    await loadMirrors();
  });
</script>

<svelte:head>
  <title>Linux 镜像管理工具</title>
</svelte:head>

<main class="max-w-4xl mx-auto p-6">
  <!-- 系统信息展示 -->
  <div class="mb-8 p-4 bg-gray-100 rounded-lg">
    <h2 class="text-xl font-semibold mb-2">当前系统</h2>
    <p class="text-gray-700">{currentDistro}</p>
  </div>

  <!-- 错误提示 -->
  {#if errorMessage}
    <div class="mb-4 p-4 bg-red-100 text-red-700 rounded-lg">
      {errorMessage}
    </div>
  {/if}

  <!-- 加载状态 -->
  {#if isLoading}
    <div class="text-center py-8">
      <div class="animate-spin inline-block w-8 h-8 border-4 border-blue-500 rounded-full border-t-transparent"></div>
      <p class="mt-2 text-gray-600">正在加载镜像列表...</p>
    </div>
  {:else}
    <!-- 镜像列表 -->
    <div class="grid gap-4">
      {#each mirrors as mirror (mirror.url)}
        <div 
          transition:fade
          class="p-4 border rounded-lg hover:shadow-md transition-shadow
            {selectedMirror === mirror.url ? 'border-blue-500 bg-blue-50' : 'border-gray-200'}"
        >
          <div class="flex items-center justify-between">
            <!-- 镜像信息 -->
            <div class="flex-1">
              <h3 class="font-medium text-gray-900">{mirror.name}</h3>
              <p class="text-sm text-gray-500 break-all">{mirror.url}</p>
              {#if mirror.latency !== null}
                <div class="mt-2">
                  <span class="inline-block px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
                    延迟: {mirror.latency}ms
                  </span>
                </div>
              {/if}
            </div>

            <!-- 操作按钮 -->
            <div class="flex gap-2 ml-4">
              <button
                on:click={() => runSpeedTest(mirror)}
                class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded-md
                      {mirror.testing ? 'animate-pulse' : ''}"
                disabled={mirror.testing}
              >
                {mirror.testing ? '测速中...' : '测速'}
              </button>
              
              <button
                on:click={() => applyMirror(mirror)}
                class="px-3 py-1 text-sm bg-blue-600 text-white hover:bg-blue-700 rounded-md"
              >
                应用
              </button>
            </div>
          </div>
        </div>
      {/each}
    </div>
  {/if}
</main>

<style>
  /* 自定义动画 */
  .animate-pulse {
    animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
  }

  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }
</style>